import { useState, useRef } from "react"

export default function App() {
  const [status, setStatus] = useState('ready')
  const audioRef = useRef(null)
  const [input, setInput] = useState('')

  async function generate() {
    const token = import.meta.env.VITE_ACCESS_TOKEN
    const APP_ID = import.meta.env.VITE_APP_ID
    const APP_KEY = import.meta.env.VITE_SECRET_KEY
    const entPoint = '/tts/api/v1/tts';
    const Header = {
      "Authorization": `Bearer;${token}`,
      'Content-Type': 'application/json'
    }
    const payload = {
      "app": {
        "appid": APP_ID,
        "token": APP_KEY,
        "cluster": "volcano_tts",
      },
      "user": {
        "uid": "uid123"
      },
      "audio": {
        "voice_type": "zh_male_junlangnanyou_emo_v2_mars_bigtts",
        "emotion": "tender",
        "encoding": "ogg_opus",
        "speed_ratio": 1.0,
        "volume_ratio": 1.0,
        "pitch_ratio": 1.0,
      },
      "request": {
        "reqid": Date.now(),
        "text": input,
        "operation": "query",
      }
    }
    setStatus('生成中...')
    const res = await fetch(entPoint, {
      method: 'POST',
      headers: Header,
      body: JSON.stringify(payload)
    })
    const data = await res.json()
    console.log(data);
    // 解析并播放音频
    function createBlobUrl(base64AudioData) {
      let byteArrays = []
      let byteCharacters = atob(base64AudioData)
      for (let offset = 0; offset < byteCharacters.length; offset++) {
        let byteArray = byteCharacters.charCodeAt(offset)
        byteArrays.push(byteArray)
      }
      let blob = new Blob([new Uint8Array(byteArrays)], { type: 'audio/mp3' })
      // console.log(URL.createObjectURL(blob));

      return URL.createObjectURL(blob)

    }
    let audioUrl = createBlobUrl(data.data)
    audioRef.current.src = audioUrl
    audioRef.current.play()

  }
  return (
    <div className="container">
      <div >
        <label htmlFor="">prompt</label>
        <button onClick={generate}>生成&播放</button>
        <textarea name="" id="" onChange={(e) => {
          setInput(e.target.value)
        }}></textarea>
      </div>
      <div className="output">
        <div>
          {status}
          <audio ref={audioRef}></audio>
        </div>
      </div>
    </div>
  )
}
